package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.List;

public class Library {
    List<LibraryItem> items = new ArrayList<LibraryItem>();

    public List<LibraryItem> getAvailableItems(LibraryItemType type) {
        List<LibraryItem> availableItems = new ArrayList<LibraryItem>();

        for(LibraryItem i : items) {
            if((type == LibraryItemType.All && i.getStatus() == Status.AVAILABLE)
                    || (i.getStatus() == Status.AVAILABLE && i.getType() == type))
                availableItems.add(i);
        }

        return availableItems;
    }

    public boolean checkoutFromLibrary(String itemTitle, UserAccount userAccount) {
        LibraryItem item = findByTitle(itemTitle);

        if(item != null && item.getStatus() == Status.AVAILABLE) {
            item.setStatus(Status.UNAVAILABLE);
            item.setItemHolder(userAccount);
            return true;
        } else {
            return false;
        }
    }

    public void addToLibrary(LibraryItem item) {
        items.add(item);
    }

    public boolean returnToLibrary(String itemToReturn) {
        LibraryItem item = findByTitle(itemToReturn);

        if(item != null && item.getStatus() == Status.UNAVAILABLE) {
            item.setStatus(Status.AVAILABLE);
            item.setItemHolder(null);
            return true;
        } else {
            return false;
        }
    }

    public List<LibraryItem> getCheckedOutItems(UserAccount userAccount) {
        List<LibraryItem> checkedOutItems = new ArrayList<LibraryItem>();
        for(LibraryItem b : items) {
            if(b.getItemHolder() == userAccount) {
                checkedOutItems.add(b);
            }
        }
        return checkedOutItems;
    }

    public LibraryItem findByTitle(String title) {
        for(LibraryItem i : items) {
            if(i.getName().equals(title)) {
                return i;
            }
        }

        return null;
    }
}
